import {
  getWebviewToken,
  queryPath,
  queryPostEditInfo,
  queryPostNewInfo,
} from '@/services/api';
import ResetPage from '@/app/[locale]/reset/reset';
import type { Metadata as MetadataNext } from 'next';
import { createError, customException, getMetadata, isNum } from '@/lib/tool';
import { notFound } from 'next/navigation';
import type { IPath, IPostEditInfo, IPostNewInfo } from '@/interfaces';
import { getTranslator } from 'next-intl/server';
import WebView from '@/app/[locale]/mp/edit/web-view';

const year = new Date().getFullYear();

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  return getMetadata({ title: '编辑文章' });
}

export default async function Page({
  params,
  searchParams: { v, tk, sid, sectionId },
}: {
  params: {
    id?: string;
    locale: string;
    navbar?: string;
    footer?: string;
    class?: string;
  };
  searchParams: { v?: 'h5'; tk?: string; sid?: string; sectionId?: string };
}) {
  try {
    const _sid = sid ?? sectionId;
    const _sectionId = _sid && isNum(_sid) ? _sid : undefined;
    const id = params.id;
    const locale = params.locale;
    params.navbar = 'false';
    params.footer = 'false';
    params.class = 'yw-mp-bg row mx-0';

    if (!tk) {
      notFound();
    }

    if (id && !isNum(id)) {
      notFound();
    }

    const token = (
      await (
        (await getWebviewToken({
          baseURL: process.env.APP_API_SERVER,
          id: tk,
        })) as Response
      ).json()
    ).data as string;

    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/mp/edit',
      },
    });

    const responses = await Promise.all([
      req1,
      id
        ? queryPostEditInfo({
            baseURL: process.env.APP_API_SERVER,
            token,
            id,
          })
        : queryPostNewInfo({
            baseURL: process.env.APP_API_SERVER,
            token,
          }),
    ]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    const path = resp1.data as IPath;
    const info = resp2.data as IPostEditInfo | IPostNewInfo;
    const t = await getTranslator(locale);
    if (!path.user) {
      return (
        <ResetPage
          error={createError(
            customException(401, t('clientPage.unauthorizedValue')),
          )}
        />
      );
    } else if (id && path.user.id !== (info as IPostEditInfo).basic.createdBy) {
      return (
        <ResetPage
          error={createError(
            customException(403, t('clientPage.forbiddenValue')),
          )}
        />
      );
    }

    return (
      <WebView
        options={{ sectionId: _sectionId, token }}
        source={info}
        editorTranslatedFields={{
          fileManager: t('postEditPage.editorDynamicPage.fileManager'),
        }}
        fileManagerTranslatedFields={{
          startUpload: t('postEditPage.fileManagerPage.startUpload'),
          selectFilePlaceholder: t(
            'postEditPage.fileManagerPage.selectFilePlaceholder',
          ),
          select: t('postEditPage.fileManagerPage.select'),
          delete: t('postEditPage.fileManagerPage.delete'),
          deleteCompleted: t('postEditPage.fileManagerPage.deleteCompleted'),
          selectFileToDelete: t(
            'postEditPage.fileManagerPage.selectFileToDelete',
          ),
          uploadCompleted: t('postEditPage.fileManagerPage.uploadCompleted'),
          fileDoesNotExist: t('postEditPage.fileManagerPage.fileDoesNotExist'),
        }}
        env={{
          appName: process.env.APP_NAME,
          appIcpNum: process.env.APP_ICP_NUM,
          appIcpLink: process.env.APP_ICP_LINK,
          year: year + '',
        }}
      />
    );
  } catch (e) {
    return <ResetPage error={createError(e)} />;
  }
}
